package com.emit.security.resultReturned;

import com.alibaba.fastjson.JSON;

import com.emit.security.ResultCode;
import com.emit.utils.Constant;
import com.emit.view.ResultView;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zhengshuai
 * @date 2021/5/25
 * @Description: 登录失败处理逻辑
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        ResultView resultView=null;
        
        //返回json数据
        if (e instanceof AccountExpiredException) {
            //账号过期
            resultView=new  ResultView(ResultCode.USER_ACCOUNT_EXPIRED);
        } else if (e instanceof BadCredentialsException) {
            //密码错误
            ResultView ResultView = new ResultView(ResultCode.USER_CREDENTIALS_ERROR);
            resultView=new  ResultView(ResultCode.USER_CREDENTIALS_ERROR);
        } else if (e instanceof CredentialsExpiredException) {
            //密码过期
            resultView=new  ResultView(ResultCode.USER_CREDENTIALS_EXPIRED);
        } else if (e instanceof DisabledException) {
            //账号不可用
            resultView=new  ResultView(ResultCode.USER_ACCOUNT_DISABLE);
        } else if (e instanceof LockedException) {
            //账号锁定
            resultView=new  ResultView(ResultCode.USER_ACCOUNT_LOCKED);
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            resultView=new  ResultView(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }else{
            //其他错误
            resultView=new  ResultView(ResultCode.COMMON_FAIL);
        }

        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType(Constant.CONTENT_TYPE);
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(resultView));
    }
}
